package com.df.resources.common;

import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

public class GatewayInstancesManager {

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private static List<Instance> instances = new ArrayList<>();


    public static Instance getOneInstance(){
        if(instances.size()==0){
            return null;
        }
        readLock.lock();
        Instance instance = null;
        try {
            List<Instance> collect = instances.stream().filter(temp -> temp.isHealthy()).collect(Collectors.toList());
            if(collect.size()==0){
                return null;
            }
            //降序排列，权重高的有限获取
            collect.sort((a,b)->(a.getWeight()-b.getWeight())>=0?-1:1);
            instance = collect.get(0);
        }finally {
            readLock.unlock();
        }

        return instance;
    }

    public static void updateInstance(List<Instance> updateInstances){
        writeLock.lock();
        try {
            for (Instance newInstance : updateInstances) {
                Optional<Instance> first = GatewayInstancesManager.instances.stream().filter(old -> old.getIp().equals(newInstance.getIp())).findFirst();
                if(!first.isPresent()){//不存在，新增的网关
                    GatewayInstancesManager.instances.add(newInstance);
                    continue;
                }
                Instance old = first.get();
                if(!newInstance.isEnabled()){//移除
                    GatewayInstancesManager.instances.remove(old);
                    continue;
                }
                //beanUtils是浅拷贝
                BeanUtils.copyProperties(newInstance,old);
                Map<String, String> metadata = old.getMetadata();
                for (String s : newInstance.getMetadata().keySet()) {
                    metadata.put(s,newInstance.getMetadata().get(s));
                }
            }
        }finally {
            writeLock.unlock();
        }

    }
}
